package level.editor.menu;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.JMenuBar;

import level.editor.command.Command;
import level.editor.mediator.Module;
import level.editor.window.View;
import level.editor.window.Window;

/*
 * Implementation of the view for the actual menu bar. A Swing object
 * responsible for transforming user input into commands to be pushed to it's
 * module.
 */

public class MenuView extends JMenuBar implements View, ActionListener
{
	private Module module;
	private ArrayList<MenuCategory> menus;

	public MenuView()
	{
		menus = new ArrayList<MenuCategory>();
	}

	@Override
	public void registerModule(Module module)
	{
		this.module = module;
	}

	public void init(Window window)
	{
		menus.add(new MenuFile(this));
		menus.add(new MenuEdit(this));
		addMenus();
		window.add(this, BorderLayout.NORTH);
	}

	private void addMenus()
	{
		if (menus.size() != 0)
		{
			for (int i = 0; i < menus.size(); i++)
			{
				add(menus.get(i));
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getActionCommand().equals("NEW"))
		{
			pushUpCommand(new StateNewCommand());
		}
		
		if (e.getActionCommand().equals("OPEN"))
		{
			pushUpCommand(new StateOpenCommand());
		}
		
		if (e.getActionCommand().equals("SAVE"))
		{
			pushUpCommand(new StateSaveCommand());
		}
		
		if (e.getActionCommand().equals("SAVEAS"))
		{
			pushUpCommand(new StateSaveAsCommand());
		}
		
		if (e.getActionCommand().equals("UNDO"))
		{
			pushUpCommand(new UndoCommand());
		}
		
		if (e.getActionCommand().equals("REDO"))
		{
			pushUpCommand(new RedoCommand());
		}
	}
	
	@Override
	public void pushUpCommand(Command command)
	{
		if (module != null && command != null)
		{
			module.pushUpCommand(command);
		}
	}
	
	@Override
	public void pushDownCommand(Command command)
	{
		if (menus.size() != 0)
		{
			for (int i = 0; i < menus.size(); i++)
			{
				menus.get(i).pushDownCommand(command);
			}
		}
	}

}
